package com.tiny.tinyweb.core.utils;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class MailUtils {
    /**
     * 用SMTP发送邮件
     * @param mailInfo 邮件信息
     * @param mailAddr 收信人地址
     * @param sessionId Session ID
     * @param smtpHost SMTP服务器Host名
     * @param smtpPort SMTP服务器端口
     * @throws Exception 发送邮件时发生的异常
     */
    public static void sendMail(Map<String, String> mailInfo, String mailAddr, final String sessionId,
            String smtpHost, String smtpPort) throws Exception {
        String fromAddr = mailInfo.get("fromAddr");
        String subject = mailInfo.get("subject");
        String name = mailInfo.get("name");
        String content = mailInfo.get("content");

        // 获取Web服务器的Host名
        final String hostName = InetAddress.getLocalHost().getHostName();

        // 设置SMTP属性
        Properties prop = new Properties();
        prop.put("mail.smtp.host", smtpHost);
        prop.put("mail.smtp.port", smtpPort);
        prop.put("mail.smtp.connectiontimeout", "30000");
        prop.put("mail.smtp.timeout", "30000");
        prop.put("mail.smtp.localhost", hostName);

        // 设置送信人和收信人地址
        Address from = null;
        Address to = null;
        if( name != null && name.length() > 0 ){
            from = new InternetAddress(fromAddr, name, "utf-8");
        } else {
            from = new InternetAddress(fromAddr);
        }
        to = new InternetAddress(mailAddr);

        // 创建邮件消息
        Session mailSession = Session.getDefaultInstance(prop);
        Message mailMessage = null;
        mailMessage = new MimeMessage(mailSession) {
            @Override
            protected void updateMessageID() throws MessagingException {
                // 改变邮件的 Message-ID
                String msgID = createMessageID(hostName, sessionId);
                if (msgID != null && !"".equals(msgID)) {
                    super.setHeader("Message-ID", msgID);
                } else {
                    super.updateMessageID();
                }
            }
        };
        mailMessage.setFrom(from);
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        mailMessage.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));
        mailMessage.setContent(content, "text/plain;charset=utf-8");
        mailMessage.setHeader("Content-Transfer-Encoding", "base64");
        // 发送邮件
        Transport.send(mailMessage);
    }

    public static void sendMailPwd(Map<String, String> mailInfo, String mailAddr, final String sessionId,
            String smtpHost, String smtpPort) throws Exception {
        String fromAddr = mailInfo.get("fromAddr");
        String subject = mailInfo.get("subject");
        String content = mailInfo.get("content");
        final String user = mailInfo.get("user");
        final String pwd = mailInfo.get("pwd");

        // 设置SMTP属性
        Properties prop = new Properties();
        prop.put("mail.smtp.host", smtpHost);
        prop.put("mail.smtp.port", smtpPort);
        prop.put("mail.smtp.connectiontimeout", "30000");
        prop.put("mail.smtp.timeout", "30000");
        prop.put("mail.smtp.auth", "true");

        // 设置送信人和收信人地址
        Address from = null;
        Address to = null;
        from = new InternetAddress(fromAddr);
        to = new InternetAddress(mailAddr);

        // 创建邮件消息
        Session mailSession = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pwd);
            }
        });
        mailSession.setDebug(true);
        Message mailMessage = null;
        mailMessage = new MimeMessage(mailSession);
        mailMessage.setFrom(from);
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        mailMessage.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));
        mailMessage.setContent(content, "text/plain;charset=utf-8");
        mailMessage.setText(content);
//        mailMessage.setHeader("Content-Transfer-Encoding", "base64");
        // 发送邮件
        Transport.send(mailMessage);
    }

    /**
     * 生成邮件的Message-ID。
     *
     * @param domain 服务器的FQDN
     * @param sessionId 当前Session的ID
     * @return 邮件的Message-ID
     */
    public static String createMessageID(String domain, String sessionId) {
        // 取得本地系统时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.CHINA);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        // 取得当前线程ID
        String threadId = String.format("%08X", Thread.currentThread().getId());
        // 生成Message-ID：系统时间yyyyMMddHHmmssSSS+SessionID后6位+当前线程ID@FQDN
        StringBuffer msgID = new StringBuffer();
        msgID.append(sdf.format(new Date()));
        msgID.append(sessionId.substring(sessionId.length() - 6));
        msgID.append(threadId.substring(threadId.length() - 4));
        msgID.append("@");
        msgID.append(domain);
        return msgID.toString();
    }
}
